# -*- coding: UTF-8 -*-
import secrets
import hashlib
import time

import requests

import settings


class ZIMAPI:
    app_id = settings.ZEGO_APP_ID
    server_secret = settings.ZEGO_APP_SECRET

    # Signature=md5(AppId + SignatureNonce + ServerSecret + Timestamp)
    def generate_signature(self, signature_nonce, timestamp):
        str1 = str(self.app_id) + signature_nonce + self.server_secret + str(timestamp)
        hash = hashlib.md5()
        hash.update(str1.encode("utf8"))
        signature = hash.hexdigest()
        return signature

    def create_user(self, users):
        signature_nonce = secrets.token_hex(8)
        timestamp = int(time.time())
        signature = self.generate_signature(signature_nonce, timestamp)
        params = {
            'Action': 'UserRegister',
            'AppId': self.app_id,
            'Timestamp': timestamp,
            'Signature': signature,
            'SignatureVersion': '2.0',
            'SignatureNonce': signature_nonce}
        data = {
            'UserInfo': users
        }
        r = requests.post('https://zim-api.zego.im', params=params, json=data)
        r.raise_for_status()

    def send_custom_message(self, from_user_id, to_user_id, sub_msg_type, message, sender_unaware=0):
        signature_nonce = secrets.token_hex(8)
        timestamp = int(time.time())
        signature = self.generate_signature(signature_nonce, timestamp)
        params = {
            'Action': 'SendPeerMessage',
            'AppId': self.app_id,
            'Timestamp': timestamp,
            'Signature': signature,
            'SignatureVersion': '2.0',
            'SignatureNonce': signature_nonce}
        data = {
            'FromUserId': from_user_id,
            'ToUserId': list([to_user_id]),
            'MessageType': 200,
            'Priority': 3,
            'MessageBody': {
                'Message': message
            },
            'SubMsgType': sub_msg_type,
            'SenderUnaware': sender_unaware
        }
        requests.post('https://zim-api.zego.im', params=params, json=data)

    def send_text_message(self, from_user_id, to_user_id, message, sender_unaware=0):
        signature_nonce = secrets.token_hex(8)
        timestamp = int(time.time())
        signature = self.generate_signature(signature_nonce, timestamp)
        params = {
            'Action': 'SendPeerMessage',
            'AppId': self.app_id,
            'Timestamp': timestamp,
            'Signature': signature,
            'SignatureVersion': '2.0',
            'SignatureNonce': signature_nonce}
        data = {
            'FromUserId': from_user_id,
            'ToUserId': list([to_user_id]),
            'MessageType': 1,
            'Priority': 3,
            'MessageBody': {
                'Message': message
            },
            'SenderUnaware': sender_unaware
        }
        requests.post('https://zim-api.zego.im', params=params, json=data)